package Farsail::EventLog;

use strict; 
use warnings;
use Log::Log4perl;
use Log::Log4perl::Layout::NoopLayout;
use Carp;

our $EVENT_TABLE = 'farsail.run_event';

my ($logger, $dblogger);

sub init {
    my $pkg = shift;
    my $farsail = shift;
    my $config = $farsail->config;
    my $db_id = $config->get('event_log.database');
    if ( !$db_id ) {
        confess "event_log.database is not set!\n";
    }
    if ( my $table = $config->get('event_log.table') ) {
        $EVENT_TABLE = $table;
    }
    my $db = $config->database($db_id);
    $dblogger = Log::Log4perl->get_logger('Event');
    $dblogger->additivity(0);
    $dblogger->level('DEBUG');
    my $app = Log::Log4perl::Appender->new(
        "Log::Log4perl::Appender::DBI",
        datasource => $db->dsn,
        username => $db->user,
        password => $db->password,
        sql => <<SQL,
INSERT INTO $EVENT_TABLE
(event_time, procid, loglevel, action, event, data)
values (?,?,?,?,?,?)
SQL
        params => {
            1 => '%d',
            2 => '%P',
            3 => '%p',
            #4 is action
            #5 is event
            #6 is message
        },
        usePreparedStmt => 1,
        bufferSize => 2,
        warp_message => 0,
    );
    $app->layout( Log::Log4perl::Layout::NoopLayout->new() );
    $dblogger->add_appender($app);
    $logger = Log::Log4perl->get_logger();
}

sub log {
    my $self = shift;
    $logger->info(join(" ", map {defined $_ ? $_ : ''} @_));
    my ($action, $event, $data) = @_;
    if ( $event =~ /error/i ) {
        $dblogger->fatal($action, $event, $data);
    } else {
        $dblogger->info($action, $event, $data);
    }
}

1;
